﻿using System;
using System.Collections.Generic;
using System.Web;
using TheOutfield.UmbExt.UniversalMediaPicker.Extensions;
using System.IO;

namespace TheOutfield.UmbExt.UniversalMediaPicker.Providers.FileSystem
{
    public class FileSystemService
    {
        private FileSystemConfig _config;

        public FileSystemService(string config)
        {
            _config = config.DeserializeJsonTo<FileSystemConfig>();
        }

        public string RootDirPath
        {
            get
            {
                return HttpContext.Current.Server.MapPath(_config.RootDir.TrimEnd('/') + "/");
            }
        }

        public IList<DirectoryInfo> GetDirectories(string path)
        {
            if (path == "-1")
            {
                var dir = new DirectoryInfo(RootDirPath);
                return dir == null ? null : new List<DirectoryInfo>(dir.GetDirectories());
            }
            else
            {
                var dir = new DirectoryInfo(Path.Combine(RootDirPath, path.Trim('\\') + "\\"));
                return dir == null ? null : new List<DirectoryInfo>(dir.GetDirectories());
            }
        }

        public IList<FileInfo> GetFiles(string path)
        {
            if (path == "-1")
            {
                var dir = new DirectoryInfo(RootDirPath);
                return dir == null ? null : new List<FileInfo>(dir.GetFiles());
            }
            else
            {
                var dir = new DirectoryInfo(Path.Combine(RootDirPath, path.Trim('\\')));
                return dir == null ? null : new List<FileInfo>(dir.GetFiles());
            }
        }

        public FileInfo GetFile(string path)
        {
            return new FileInfo(Path.Combine(RootDirPath, path.Trim('\\')));
        }
    }
}